package com.monolithiot.cdn.management.common.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 2018/11/19 Create by 郭文梁
 * UploadFileUtil
 * 文件上传工具类
 *
 * @author 郭文梁
 * @date 2018/11/19
 */
public class UploadFileUtil {
    /**
     * 后缀名分隔符
     */
    private static final String DELIMITER_DOT = ".";

    /**
     * 生成随机UUID文件名
     *
     * @param file multipart file
     * @return 文件名
     */
    public static String randomUUIDFileName(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String suffix = suffix(filename);
        return IdentityUtil.randomUUID() + suffix;
    }

    /**
     * 获取文件后缀名
     *
     * @param filename 原文件名
     * @return 后缀名
     */
    private static String suffix(String filename) {
        if (filename.contains(DELIMITER_DOT)) {
            int dotIndex = filename.lastIndexOf(DELIMITER_DOT);
            return filename.substring(dotIndex);
        }
        return "";
    }

    public static String copyTmpToPath(MultipartFile zipFile, String path) throws IOException {
        String targetFileName = randomUUIDFileName(zipFile);
        File targetFile = new File(path, targetFileName);
        zipFile.transferTo(targetFile);
        return targetFileName;
    }
}
